// src/App.tsx
import { useState } from 'react';
import { Form, Input, Button, message } from 'antd';
import { UserOutlined, LockOutlined } from '@ant-design/icons';
import { Link, useNavigate } from 'react-router-dom';
import './App.css';

function App() {
  const navigate = useNavigate();
  const [loading, setLoading] = useState(false);

  const onFinish = async (values: { username: string; password: string }) => {
    setLoading(true);
    try {
      const response = await fetch('/api/users/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          username: values.username,
          password: values.password,
        }),
      });

      // 检查HTTP状态码
      if (!response.ok) {
        if (response.status === 401) {
          message.error('用户名或密码错误');
        } else if (response.status === 400) {
          message.error('请求参数错误');
        } else if (response.status >= 500) {
          message.error('服务器错误，请稍后重试');
        } else {
          message.error(`登录失败，错误码: ${response.status}`);
        }
        return;
      }

      const result = await response.json();
      console.log('登录响应:', result);

      // 验证响应数据
      if (result.token && result.userId && result.username) {
        // 存储所有必要的用户信息
        localStorage.setItem('token', result.token);
        localStorage.setItem('userId', result.userId.toString());
        localStorage.setItem('uid', result.uid || '');
        localStorage.setItem('username', result.username);
        
        console.log('存储的用户信息:', {
          token: result.token,
          userId: result.userId,
          uid: result.uid,
          username: result.username
        });
        
        message.success(result.message || '登录成功！');
        navigate('/home');
      } else {
        // 响应数据不完整
        console.error('登录响应数据不完整:', result);
        message.error('登录失败，服务器返回数据异常');
      }
    } catch (error) {
      console.error('网络错误:', error);
      if (error instanceof TypeError) {
        message.error('网络连接失败，请检查后端服务是否开启');
      } else {
        message.error('登录过程发生异常');
      }
    } finally {
      setLoading(false);
    }
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log('表单校验失败:', errorInfo);
    message.error('请正确填写表单信息');
  };

  const iconStyle = { color: '#e8d9c7' };
  const inputStyle = {
    backgroundColor: '#FFFFFF',
    borderColor: '#e8d9c7',
    borderWidth: '2px',
    borderRadius: '20px',
    height: '42px',
    fontSize: '14px',
  };

  return (
    <div
      className="login-page"
      style={{
        backgroundImage: "url('/background.jpg')",
        backgroundSize: 'cover',
        backgroundPosition: 'center',
        backgroundRepeat: 'no-repeat',
        height: '100vh',
        display: 'flex',
        justifyContent: 'flex-end',
        alignItems: 'center',
        paddingRight: '10%',
        boxSizing: 'border-box',
      }}
    >
      <div className="login-form">
        <div className="logo">
          <img src="/logo.png" alt="食悟 Logo" style={{ maxWidth: '150px' }} />
        </div>

        <Form
          name="login"
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          style={{ width: '100%' }}
          autoComplete="off"
        >
          <Form.Item
            name="username"
            rules={[
              { required: true, message: '请输入用户名!' },
              { min: 2, message: '用户名至少2个字符' },
              { max: 20, message: '用户名最多20个字符' }
            ]}
          >
            <Input
              prefix={<UserOutlined style={iconStyle} />}
              placeholder="请输入用户名"
              style={inputStyle}
              autoComplete="username"
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[
              { required: true, message: '请输入密码!' },
              //{ min: 6, message: '密码至少6个字符' }
            ]}
          >
            <Input.Password
              prefix={<LockOutlined style={iconStyle} />}
              placeholder="请输入密码"
              style={inputStyle}
              autoComplete="current-password"
            />
          </Form.Item>

          <Form.Item>
            <Button
              type="primary"
              htmlType="submit"
              block
              loading={loading}
              disabled={loading}
              style={{
                backgroundColor: '#e8d9c7',
                borderColor: '#e8d9c7',
                color: '#555',
                fontWeight: 'bold',
                padding: '12px 24px',
                height: '42px',
                borderRadius: '20px',
                fontSize: '16px',
              }}
            >
              {loading ? '登录中...' : '登录'}
            </Button>
          </Form.Item>
        </Form>

        <div style={{ textAlign: 'center', marginTop: '16px' }}>
          <Link 
            to="/register" 
            className="register-link"
            style={{
              color: '#e8d9c7',
              textDecoration: 'none',
              fontSize: '14px',
            }}
          >
            还没有账号？点击注册
          </Link>
        </div>
      </div>
    </div>
  );
}

export default App;